import type { RouteRecordRaw, Router } from "vue-router";
import type { SiderMenus } from "@/layout/layout";
// import { BasicLayout } from "@/layout";
import FallBack404 from "@/views/not-found.vue";

import { getMenus } from "@/api/auth/login";
import { preferences } from "@/config/preference";
import { useAccessStore } from "@/store";

// 通过文件路径生成组件名
function generateComponentName(filePath: string) {
  return (
    filePath
      .replace("/src/views/", "")
      .replace("/index.vue", "")
      .replace(".vue", "")
      .replace(/(^|\/|-)([a-z])/g, (_, p1, p2) => {
        return p1 + p2.toUpperCase();
      })
      .replace("-", "")
      .split("/")
      .reverse()
      .join("") + "View"
  );
}

// 动态路由和菜单
function generateDynamicRoutes(meuns: Api.Menus[], parentPath = "/") {
  const pageMap = import.meta.glob(["@/views/**/!(modules)/*.vue", "!@/views/login/*.vue"]);
  // console.log("mmmm: ", pageMap, Object.keys(pageMap));

  function getPageComponent(path: string) {
    let key = ["/src/views", path, "index.vue"].join("/");
    return pageMap[key] ?? pageMap[key.replace("/index", "")] ?? FallBack404;
  }

  function generateChildren(routes: Api.Menus[]) {
    const siderMenus: SiderMenus[] = [];
    const dynamicRoutes: RouteRecordRaw[] = [];
    routes.forEach((item) => {
      let menuItem: SiderMenus = {
        name: item.name,
        path: item.path,
        icon: item.source,
      };
      siderMenus.push(menuItem);
      if (item.children && item.children.length > 0) {
        let { menus: m, dynamicRoutes: r } = generateChildren(item.children);
        menuItem["children"] = m;
        dynamicRoutes.push(...r);
      } else {
        let re = new RegExp(`^${parentPath}`);
        let path = item.path.replace(re, "");
        // console.log("item: ", item);
        let comp = getPageComponent(path);
        let name = comp === FallBack404 ? path : generateComponentName(path);
        dynamicRoutes.push({
          path,
          name,
          component: comp,
          meta: {
            label: item.name,
            componentName: name,
            cache: item?.cache ?? true,
          },
        });
      }
    });
    return {
      dynamicRoutes: dynamicRoutes,
      menus: siderMenus,
    };
  }

  return generateChildren(meuns);
}

function addDynamicRoutes(router: Router, routes: RouteRecordRaw[]) {
  const rootRoute = router.getRoutes().find((item) => preferences.app.root === item.name)!;
  const notFoundRoute = router.getRoutes().find((item) => preferences.app.notFound === item.name)!;
  router.removeRoute(preferences.app.notFound);
  rootRoute["children"] = routes;
  router.addRoute(rootRoute);
  router.addRoute(notFoundRoute);
}

// 生成路由和菜单
export async function generateAccess(router: Router) {
  const accessStore = useAccessStore();
  const [err, res] = await getMenus({ loading: true });
  if (!err) {
    const { dynamicRoutes, menus } = generateDynamicRoutes(res);
    // console.log("dynamicRoutes: ", dynamicRoutes);
    accessStore.setAccessRoute(dynamicRoutes.map((i) => i.path));
    accessStore.setAccessMenu(menus);
    addDynamicRoutes(router, dynamicRoutes);
  }
}
